package com.douwan.ap;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebView.HitTestResult;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class Web extends Activity {

	private WebView web = null;
	private ProgressDialog dialog = null;
	private ProgressBar pb = null;
	private Handler myHandler = null;
	private Thread web_back = null;
	
	private final int WEB_BACK = 1;
	private long new_time = 0;
	private int redirect_num = 0;
	private String no_redirect = "-1";
	private boolean response_succeed = true;
	
	@SuppressLint({ "SetJavaScriptEnabled", "HandlerLeak" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout);
		
		pb = (ProgressBar)findViewById(R.id.progressbar);
		pb.setMax(100);
		
		web = (WebView)findViewById(R.id.webview);
		web.getSettings().setJavaScriptEnabled(true);
		web.getSettings().setBlockNetworkImage(true); 
//		web.getSettings().setUserAgentString("Mozilla/5.0 (iPhone; CPU iPhone OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12H143");
		
		myHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				Intent it = new Intent("com.douwan.ap.mainActivity");
				switch(msg.what)
				{
				case WEB_BACK:
					it.putExtra("mainActivity","web_back");
					it.putExtra("time",new_time);
					it.putExtra("redirect", no_redirect);
					sendBroadcast(it);
					Log.i("debug.info", "web---sendBroadcast:web_back");
					finish();
					break;
				default :
					break;
				}
			}
			
		};
		
		Intent it = getIntent();
		Bundle bd = it.getExtras();
		String uri = bd.getString("uri");
		if(web != null)
        {
			web.setWebChromeClient(new WebChromeClient()
			{
				public void onProgressChanged(WebView view, int progress)
				{           
					Web.this.setTitle(view.getUrl());
					Web.this.setProgress(progress * 100);
					pb.setProgress(progress);
					if(progress == 100)
					{
						pb.setProgress(View.GONE-100);
//						Log.i("debug.info","url:"+view.getUrl());
						Web.this.setTitle(view.getUrl());
	                }
	             }
			}); 
			
			web.setWebViewClient(new WebViewClient()
			{
				@Override
				public void onPageFinished(WebView view,String url)
				{
					MyThread mythread = new MyThread();
					web_back = new Thread(mythread);
					web_back.setDaemon(true);
					
					view.getSettings().setBlockNetworkImage(false);
					new_time = SystemClock.uptimeMillis();
					redirect_num = redirect_num +1;
					Log.i("debug.info","url:"+view.getUrl()+"  redirect number:"+redirect_num);
					if(redirect_num ==1 && response_succeed == false)
					{
						web_back.start();
					}
					if(redirect_num == 2)
					{
						
						web_back.start();
					}
					dialog.dismiss();
					
				}
				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String url) 
				{					
					HitTestResult hit = view.getHitTestResult();
					if (hit != null) 
					{
						int hitType = hit.getType();
						Log.i("debug.info", "hitType:" + hitType);
						if (hitType == 0) 
						{
							no_redirect = hitType + "";
						}
					}
					if (url != null) 
					{
						view.loadUrl(url);
					}
					return true;
				}
				@Override
				public void onReceivedError(WebView view, int errorCode,
						String description, String failingUrl){ 
					// TODO Auto-generated method stub
					response_succeed = false;
					Log.i("debug.info","failingUrl:"+failingUrl+" description:"+description+" errorCode:"+errorCode);
					super.onReceivedError(view, errorCode, description, failingUrl);
				}	
				
			});
			loadUrl(uri);
        }
		
	}
	
	public class MyThread implements Runnable
	{
		@Override
		public void run() {
			Message message = new Message();
			try {
				Thread.sleep(8*1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(response_succeed == false)
				no_redirect = "-2";
			message.what = WEB_BACK;
			myHandler.sendMessage(message);
    
		}
		
	} 
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if (keyCode == KeyEvent.KEYCODE_BACK || web.canGoBack()) 
		{  
			//web.goBack();
            return false;  
        } 
		return super.onKeyDown(keyCode, event);
	}

	public void loadUrl(final String url)
    {	 
		
		if(web != null)
		{ 
			web.loadUrl(url);
//			web.reload();
			dialog = ProgressDialog.show(this,null,"页面加载中，请稍后.."); 
      	
		}
    }
}
